﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CustomControls
{
    /// <summary>
    /// 居中排列控件的面板，支持自动换行
    /// </summary>
    public class CenterPanel : Panel
    {
        #region 私有字段
        private int _spacing = 5;        // 控件间距
        private int _rowSpacing = 10;    // 行间距
        private bool _autoSize = true;   // 是否自动调整面板大小
        #endregion

        #region 构造函数
        public CenterPanel()
        {
            // 启用双缓冲减少闪烁
            this.DoubleBuffered = true;
            this.ResizeRedraw = true;

            // 初始化布局
            this.ControlAdded += CenterPanel_ControlAdded;
            this.ControlRemoved += CenterPanel_ControlRemoved;
            this.Resize += CenterPanel_Resize;
        }
        #endregion

        #region 事件处理
        private void CenterPanel_ControlAdded(object sender, ControlEventArgs e)
        {
            PerformLayout();
        }

        private void CenterPanel_ControlRemoved(object sender, ControlEventArgs e)
        {
            PerformLayout();
        }

        private void CenterPanel_Resize(object sender, EventArgs e)
        {
            PerformLayout();
        }
        #endregion

        #region 布局逻辑
        protected override void OnLayout(LayoutEventArgs levent)
        {
            base.OnLayout(levent);

            if (this.Controls.Count == 0)
                return;

            LayoutControls();
        }

        private void LayoutControls()
        {
            List<List<Control>> rows = new List<List<Control>>();
            List<Control> currentRow = new List<Control>();
            int currentRowWidth = 0;
            int maxRowHeight = 0;

            // 按行分组控件
            foreach (Control control in this.Controls)
            {
                if (control.Visible)
                {
                    int requiredWidth = currentRowWidth + control.Width + (currentRow.Count > 0 ? _spacing : 0);

                    // 如果当前控件无法放入当前行，则创建新行
                    if (currentRow.Count > 0 && requiredWidth > this.ClientSize.Width)
                    {
                        rows.Add(currentRow);
                        currentRow = new List<Control>();
                        currentRowWidth = 0;
                        maxRowHeight = 0;
                    }

                    currentRow.Add(control);
                    currentRowWidth = requiredWidth;
                    maxRowHeight = Math.Max(maxRowHeight, control.Height);
                }
            }

            // 添加最后一行
            if (currentRow.Count > 0)
            {
                rows.Add(currentRow);
            }

            // 布局每行控件
            int y = _rowSpacing;
            int totalHeight = 0;

            foreach (var row in rows)
            {
                int rowWidth = 0;
                int rowHeight = 0;

                // 计算行宽和行高
                foreach (var control in row)
                {
                    rowWidth += control.Width;
                    rowHeight = Math.Max(rowHeight, control.Height);
                }

                // 添加间距
                rowWidth += (row.Count - 1) * _spacing;

                // 计算起始X坐标（居中）
                int x = (this.ClientSize.Width - rowWidth) / 2;

                // 布局当前行的控件
                foreach (var control in row)
                {
                    control.Location = new Point(x, y + (rowHeight - control.Height) / 2);
                    x += control.Width + _spacing;
                }

                // 更新Y坐标
                y += rowHeight + _rowSpacing;
                totalHeight += rowHeight + _rowSpacing;
            }

            // 如果启用了自动调整大小，则设置面板高度
            if (_autoSize && rows.Count > 0)
            {
                this.Height = totalHeight - _rowSpacing + 10 + this.Padding.Vertical;
            }
        }
        #endregion

        #region 公共属性
        /// <summary>
        /// 获取或设置控件之间的间距
        /// </summary>
        [Category("布局")]
        [Description("控件之间的间距")]
        [DefaultValue(5)]
        public int Spacing
        {
            get { return _spacing; }
            set
            {
                if (_spacing != value)
                {
                    _spacing = value;
                    PerformLayout();
                }
            }
        }

        /// <summary>
        /// 获取或设置行之间的间距
        /// </summary>
        [Category("布局")]
        [Description("行之间的间距")]
        [DefaultValue(10)]
        public int RowSpacing
        {
            get { return _rowSpacing; }
            set
            {
                if (_rowSpacing != value)
                {
                    _rowSpacing = value;
                    PerformLayout();
                }
            }
        }

        /// <summary>
        /// 获取或设置是否自动调整面板大小以适应内容
        /// </summary>
        [Category("布局")]
        [Description("是否自动调整面板大小以适应内容")]
        [DefaultValue(true)]
        public bool AutoSize
        {
            get { return _autoSize; }
            set
            {
                if (_autoSize != value)
                {
                    _autoSize = value;
                    PerformLayout();
                }
            }
        }
        #endregion
    }
}
